<?php

/**
 * 商户的消费记录
 * User: csyr
 * Date: 6/25/16
 * Time: 15:25
 */

namespace Home\Model;
use Common\Library\BusinessException;
use Think\Log;
use Think\Model;
use Common\Library\Constant;
use Common\Library\CacheRedis;

class ConsumeHistoryModel extends Model{

    const STATUS_UN_REVIEWED = 0; //没有审核
    const STATUS_REVIEWED = 1; //已完成
    const STATUS_DOWN_PAYMENT = 2; //待缴首付
    const STATUS_PAY_OK = 3; //已还款
    const STATUS_NEXT_INSTALL = 4; //次月转分期
    const STATUS_WAIT_REVIEWED = 21; //子豪脚本待审核           目前正在测试   试用21
//    const STATUS_WAIT_REVIEWED = 5; //市场待审核
    const STATUS_WAIT_REVIEWEDS = 23; //展达脚本待审核
    const STATUS_WAIT_REVIEWEDSS = 24; //市场待审核
    const STATUS_WAIT_REVIEWEDA = 5; //为了兼容处理用的中间值
    const STATUS_REVIEW_FAILED = 6; //人工拒绝
    const STATUS_TONDDUN_FAILED = 7; //决策执行失败
    const STATUS_WAITING_REPAY = 8; //待借款or待打款
    const STATUS_CANCEL = 9; //已取消
    const STATUS_WAIT_TWO = 10; //信审待审核
    const STATUS_JIUFU_FAILED = 11; //玖富资金引擎失败
    const STATUS_JUJUE = 11; //系统自动拒绝
    const STATUS_CASH_REVIEWED = 12; //提现申请通过
    const STATUS_CASH_FAILED = 13; //提现失败
    const STATUS_REVIEW_CANCEL = 14; //信审贷前信息不合格
    const STATUS_SEND_GOODS = 15; //发货照片待上传
    const STATUS_SEND_MONEY_WAITING = 16; //待放款
    const STATUS_SEND_MONEY_FAILED = 17; //放款信息不合格
    const STATUS_CASH_AUTO_REVIEWED = 18; //系统自动审核通过
    const STATUS_FAXI = 0.02;


    /**
     * 本月账单还款时间
     * @param int $month
     * @return int
     */
    public function getRepaymentTime($month = 1)
    {
       return strtotime(date('Y-m-' . Constant::BILL_LAST_DAY . ' 00:00:00', strtotime("+{$month}month")));
    }

    /**
     * 获取订单详情
     */
    public function getConsumeHistory($consumeId, $status = 5){
        $sql = 'SELECT
                    m.id,
                    m. NAME,
                    ch.amount,
                    ch.consume_amount,
                    ch.discount_first_order,
                    ch.discount_full_reduce,
                    ch.discount_rebate_amount,
                    FROM_UNIXTIME(ch.add_time, "%Y-%m-%d") AS add_time,
                    FROM_UNIXTIME(ch.repayment_time,"%Y-%m-%d"
                    ) AS repayment_time,
                    ch.type
                FROM
                    consume_history ch
                LEFT JOIN merchant m ON ch.merchant_id = m.id
                WHERE
                    ch.id = '.$consumeId.' AND ch.status='.$status;
        $res = $this->query($sql);
        return $res;
    }

    public function getConsumeCountByCustomerId($customer_id){
        $sql = "SELECT
                  count(1) AS cnt
                FROM
                  consume_history c
                LEFT JOIN merchant m ON c.merchant_id = m.id
                WHERE
                  customer_id = ".$customer_id." AND type IN (1, 2) ORDER BY c.id DESC";
        $res = M()->query($sql);
        return $res;
    }

    public function getWithdrawalCountByCustomerId($customer_id){
        $sql = "SELECT
                  count(1) AS cnt
                FROM
                  consume_history c
                WHERE
                  customer_id = ".$customer_id." AND type = 5 AND status IN (1,3)";
        $res = M()->query($sql);
        return $res;
    }

    public function getConsumeListByCustomerId($customer_id, $offset, $length, $where_status = NULL){
        $sql = "SELECT
                  c.id AS consume_id,
                  c.type AS repay_type,
                  c.add_time,
                  FROM_UNIXTIME(c.add_time,'%Y-%m-%d %H:%i:%s') AS consume_date,
                  FROM_UNIXTIME(c.repayment_time,'%Y-%m-%d %H:%i:%s') AS repay_date,
                  c.amount AS real_pay,
                  c.discount_first_order,
                  c.discount_full_reduce,
                  c.discount_rebate_amount,
                  c.down_payment,
                  c.amount+c.down_payment as show_amount,
                  c. status,
                  m.`name` AS merchant_name,
                  m.logo AS merchant_logo,
                  m.add_time AS create_time,
                  c.merchant_id,
                  c.consume_amount,
                  c.customer_id
                FROM
                  consume_history c
                LEFT JOIN merchant m ON c.merchant_id = m.id
                WHERE
                  customer_id = ".$customer_id." AND type IN (1, 2)";
        if($where_status){
            $sql .= " AND c.status in (".$where_status.")";
        }
        $sql .= "ORDER BY c.id DESC
                LIMIT ".$offset.", ".$length;
        Log::write("付款记录sql：".$sql, Log::INFO);
        $res = M()->query($sql);
        return $res;
    }

    public function getWithdrawalListByCustomerId($customer_id, $offset, $length, $where_status=NULL, $type=5){
        $sql = "SELECT
                  c.id AS consume_id,
                  FROM_UNIXTIME(c.add_time,'%Y-%m-%d %H:%i:%s') AS consume_time,
                  c.consume_amount AS amount,
                  c.amount AS apply_amount,
                  p.repay_times,
                  p.timer,
                  p.repay_times,
                  p.repay_unit,
                  p.cut_interest,
                  c.repay_id,
                  c. status,
                  c.repayment_time
                FROM
                  consume_history c
                LEFT JOIN sys_installment_plan p ON c.repay_id = p.id
                WHERE
                  c.customer_id = ".$customer_id." ";
        
//         $sql = "SELECT
//                   c.id AS consume_id,
//                   FROM_UNIXTIME(c.add_time,'%Y-%m-%d %H:%i:%s') AS consume_time,
//                   c.consume_amount AS amount,
//                   c.amount AS apply_amount,
//                   p.repay_times,
//                   c. status
//                 FROM
//                   consume_history c
//                 LEFT JOIN sys_installment_plan p ON c.repay_id = p.id
//                 WHERE
//                   c.customer_id = ".$customer_id." AND c.type = ".$type;
        if($where_status){
            $sql .= " AND c.status in (".$where_status.")";
        }
        $sql .= " ORDER BY c.add_time DESC
                LIMIT ".$offset.", ".$length;
        Log::write("提现记录sql1：".$sql, Log::INFO);
//         echo $sql;
        $res = M()->query($sql);
        return $res;
    }

    public function getAdminConfigInfo()
    {
      $adminConfigInfo = M("admin_config",null)->field('name,extra')->select();
        foreach ($adminConfigInfo as $key => $config) {
          if ($config['name'] == 'COPYRIGHT') {
            $data['copyright'] = $config['extra'];//版权链接
          } elseif ($config['name'] == 'OFFLINE_REPAYMENT') {
            $data['offlinerepayment'] = $config['extra'];//线下还款链接
          } elseif ($config['name'] == 'REFUSE_URL') {
            $data['url'] = $config['extra'];//放款失败导流链接，拒贷导流链接
          } elseif ($config['name'] == 'SWITCH_STATUS') {
            $data['switch_status'] = $config['extra'];//临时导流开关
          } elseif ($config['name'] == 'NOTICE') {
            $data['notice'] = $config['extra'];//活动信息提示
          }
        }
        return $data;
    }

    public function getCurOrderStatus($res, $model=NULL){
        $data['status'] = $res['status'] ? $res['status'] : 1;

        $data['consume_id'] = $res['consume_id'] ? $res['consume_id'] : 0;
        $repayment_time = $res['repayment_time'] ? $res['repayment_time'] : 0;

        if($data['status'] == ConsumeHistoryModel::STATUS_CASH_REVIEWED){
            $cache = CacheRedis::getKey($res['customer_id'], Constant::PAY_TYPE_WITHDRAWAL_APPLY);
            $data['need_pop'] = $cache ? 1 : 0;
            $data['timer'] = $res['timer'] ? $res['timer'] : '';
            $data['repay_times'] = $res['repay_times'] ? $res['repay_times'] : '';
            $data['repay_unit'] = $res['repay_unit'] ? $res['repay_unit'] : '';
            $data['withdrawal_amount'] = $res['amount'] ? $res['amount'] : '';
            $cut_interest = $res['cut_interest'] ? $res['cut_interest'] : '';
            $data['transfer_amount'] = $res['apply_amount'] ? $res['apply_amount'] : '';
            $data['repay_total'] = $res['amount'] ? $res['amount'] : '';//这是一个每期还款数  目前让他等于借钱数
            $data['fee_amount'] = $data['withdrawal_amount']*$cut_interest;
            $data['repay_id'] = $res['repay_id'] ? $res['repay_id'] : '';
        }elseif($data['status'] == ConsumeHistoryModel::STATUS_REVIEW_FAILED || $data['status'] == ConsumeHistoryModel::STATUS_TONDDUN_FAILED){
            $data['reason'] = Constant::TIPS_ORDER_FAILED;
            
            foreach ($adminConfigInfo as $key => $config) {
              if ($config['name'] == 'REFUSE_URL') {
                $data['url'] = $config['extra'];//放款失败导流链接，拒贷导流链接
              }
            }
            $real_reason = M('CreditVetting')->where(['customer_id'=>$res['customer_id'], 'consume_id'=>$res['consume_id'], 'status'=>4])->find();
            Log::write("real_reason_sql=:".M('CreditVetting')->getLastSql(), Log::DEBUG);
            if($real_reason){
                $data['reason'] = $real_reason['reason'];
            }
        }elseif($data['status'] == ConsumeHistoryModel::STATUS_DOWN_PAYMENT){
            $data['down_payment'] = $res['down_payment'];
            $data['type'] = $res['repay_type'];
            //获取用户银行卡信息
            $bank = D('CustomerBankInfo')->getList($res['customer_id']);
            Log::write("==".json_encode($bank), Log::DEBUG);
            if(!$bank){
                $data['bind_card'] = 0; //未绑定银行卡
            }else{
                $data['bind_card'] = 1; //绑定银行卡
                $data['card_num'] = $bank[0]['card_num'];
                $data['bank_name'] = $bank[0]['card_user_name'];
            }
        } elseif ($res['status'] == ConsumeHistoryModel::STATUS_REVIEWED){
            $consume_id = $data['consume_id'];
            $detail = M('ConsumeInstallmentHistory')->order('repayment_time')->where(['parent_id' => $consume_id, 'status' => 0])->
            field('allow_renew,DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date')->find();
            Log::write("+++++++++++++++sql=".M()->getLastSql()."+++++++".json_encode($detail)."++++++++");
            $data['allow_renew'] = $detail['allow_renew'];
            if ($detail['fine_date'] < 0){
                $data['day_remaining'] = substr($detail['fine_date'],1);
                $data['overdue'] = 1;
            } else {
                $data['day_remaining'] = $detail['fine_date'];
                $data['overdue'] = 0;
            }
            $data['final_day'] = date("Y-m-d", $repayment_time);//还款日期
            $data['timer'] = $res['timer'] ? $res['timer'] : '';
            $data['withdrawal_amount'] = $res['amount'] ? $res['amount'] : '';
            $cut_interest = $res['cut_interest'] ? $res['cut_interest'] : '';
            $data['transfer_amount'] = $res['apply_amount'] ? $res['apply_amount'] : '';
            $data['repay_total'] = $res['amount'] ? $res['amount'] : '';//这是一个每期还款数  目前让他等于借钱数
            $data['fee_amount'] = $data['withdrawal_amount']*$cut_interest;
            $data['repay_id'] = $res['repay_id'] ? $res['repay_id'] : '';
        }

        if($data['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWED || $data['status'] == ConsumeHistoryModel::STATUS_WAIT_TWO ||
            $data['status'] == ConsumeHistoryModel::STATUS_SEND_GOODS || $data['status'] == ConsumeHistoryModel::STATUS_SEND_MONEY_WAITING ||
            $data['status'] == ConsumeHistoryModel::STATUS_SEND_MONEY_FAILED || $data['status'] == ConsumeHistoryModel::STATUS_REVIEW_CANCEL ||
            $data['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWEDS || $data['status'] == ConsumeHistoryModel::STATUS_WAIT_REVIEWEDSS){
            if($res['repay_type'] == Constant::PAY_TYPE_INSTALLMENT || $res['repay_type'] == Constant::PAY_TYPE_NEXT_MONTH) {
                $data['amount'] = $res['real_pay'];
                $data['add_time'] = $res['consume_date'];
                $data['type'] = $res['repay_type'];
                $data['merchant_id'] = $res['merchant_id'];
                $data['merchant_name'] = $res['merchant_name'];
                $data['consume_amount'] = $res['consume_amount'];
                $data['reduce_amount'] = $res['discount_first_order'] + $res['discount_full_reduce'] + $res['discount_rebate_amount'];
                $data['repayment_time'] = $res['repay_date'];
                $data['status'] = ConsumeHistoryModel::STATUS_WAIT_REVIEWEDA;
            }else{
                $data['amount'] = $res['amount'];
                $data['consume_id'] = $res['consume_id'];
            }
        }

        return $data;
    }

    /****** 校验用户当前是否为逾期未还款，是则不允许下单 ******/
    public function chkFineOrWaitReview($customerId){
        $sql = "SELECT id FROM consume_history
                WHERE
                    customer_id = ".$customerId."
                  AND type IN (1, 2)
                  AND ( status in (".ConsumeHistoryModel::STATUS_WAIT_REVIEWED.",
                  ".ConsumeHistoryModel::STATUS_WAIT_REVIEWEDS.",
                  ".ConsumeHistoryModel::STATUS_WAIT_REVIEWEDSS.",
                  ".ConsumeHistoryModel::STATUS_WAIT_TWO.",
                  ".ConsumeHistoryModel::STATUS_WAITING_REPAY.",
                  ".ConsumeHistoryModel::STATUS_DOWN_PAYMENT.",
                  ".ConsumeHistoryModel::STATUS_SEND_GOODS.",
                  ".ConsumeHistoryModel::STATUS_SEND_MONEY_WAITING.",
                  ".ConsumeHistoryModel::STATUS_SEND_MONEY_FAILED.",
                  ".ConsumeHistoryModel::STATUS_REVIEW_CANCEL.")
                  OR (
                    status IN (".ConsumeHistoryModel::STATUS_REVIEWED.",".ConsumeHistoryModel::STATUS_NEXT_INSTALL.")
                    AND FROM_UNIXTIME(repayment_time, '%Y-%m-%d') <= '".date('Y-m-d', time())."'
                  ))";
        $res = M()->query($sql);
        Log::write("逾期or待审核结果：res=".json_encode($res), Log::DEBUG);

        return $res;
    }

    /****** 校验现金贷用户当前是否为逾期未还款，是则不允许下单 ******/
    public function chkWithdFineOrWaitReview($customerId){
        //查询有没有待审核的现金贷订单
        $sql = "SELECT id FROM consume_history
                WHERE
                    customer_id = ".$customerId."
                  AND type = 4
                  AND status in (".ConsumeHistoryModel::STATUS_WAIT_REVIEWED.",".ConsumeHistoryModel::STATUS_WAIT_REVIEWEDS.",".ConsumeHistoryModel::STATUS_WAIT_REVIEWEDSS.", ".ConsumeHistoryModel::STATUS_TONDDUN_FAILED.", ".ConsumeHistoryModel::STATUS_WAIT_TWO.")";
        $res = M()->query($sql);

        //查询有没有逾期未还款的订单
        if(!$res){
            $sql = "SELECT id FROM consume_history
                WHERE
                    customer_id = ".$customerId."
                  AND type = 5
                  AND status = ".ConsumeHistoryModel::STATUS_REVIEWED."
                  AND FROM_UNIXTIME(repayment_time, '%Y-%m-%d') <= '".date('Y-m-d', time())."'";
            $res = M()->query($sql);
        }
        Log::write("逾期or待审核结果：res=".json_encode($res), Log::DEBUG);

        return $res;
    }

    public function getReviewList($offset, $length, $county_id_str){
        $sql_count = "SELECT COUNT(1) AS cnt
                FROM
                  consume_history h
                LEFT JOIN customer c ON h.customer_id = c.id
                LEFT JOIN merchant m ON h.merchant_id = m.id
                WHERE
                    h.status in (".$this::STATUS_WAIT_REVIEWED.",".$this::STATUS_WAIT_REVIEWEDSS.",".$this::STATUS_WAIT_REVIEWEDS.",".$this::STATUS_REVIEW_CANCEL.")
                AND h.consume_amount > 0 AND h.type IN (".Constant::PAY_TYPE_NEXT_MONTH.", ".Constant::PAY_TYPE_INSTALLMENT.")";
        if($county_id_str){
            $sql_count .= " AND h.county_id IN (".$county_id_str.") ";
        }
        $count = $this->query($sql_count);

        $sql = "SELECT
                  m.name AS merchant_name,
                  c.real_name AS customer_name,
                  c.mobile,
                  c.gender,
                  FROM_UNIXTIME(h.add_time, '%Y-%m-%d %H:%i:%s') AS consume_time,
                  h.type,
                  h.amount,
                  h.id,
                  c.id as customer_id,
                  h.status,
                  h.goods_name
                FROM
                  consume_history h
                LEFT JOIN customer c ON h.customer_id = c.id
                LEFT JOIN merchant m ON h.merchant_id = m.id
                WHERE
                    h.status in (".$this::STATUS_WAIT_REVIEWED.",".$this::STATUS_WAIT_REVIEWEDS.",".$this::STATUS_WAIT_REVIEWEDSS.",".$this::STATUS_REVIEW_CANCEL.")
                AND h.consume_amount > 0 AND h.type IN (".Constant::PAY_TYPE_NEXT_MONTH.", ".Constant::PAY_TYPE_INSTALLMENT.") ";
        if($county_id_str){
            $sql .= " AND h.county_id IN (".$county_id_str.") ";
        }
        $sql .= "ORDER BY h.id desc LIMIT ".$offset.", ".$length;
        Log::write("sql=".$sql, Log::DEBUG);
        $res = $this->query($sql);

        if($res){
            foreach($res as $k=>$v){
                $res[$k]['upload_customer_admin'] = 0;
                $res[$k]['upload_customer_goods'] = 0;
                $Model = M('UploadConsumeRes');
                $upload = $Model->alias('r')
                    ->join('upload_file f ON f.id = r.upload_id')
                    ->where('r.consume_id='.$v['id'])->select();
                Log::write("sql=".$Model->getLastSql(), Log::DEBUG);
                foreach ($upload as $uv){
                    if($uv['type'] == constant::CERT_ORDER_CUSTOMER_ADMIN && $res[$k]['upload_customer_admin'] != 1){
                        $res[$k]['upload_customer_admin'] = $uv['publish']==1 ? 1: -1;
                    }else if($uv['type'] == constant::CERT_ORDER_CUSTOMER_GOODS && $res[$k]['upload_customer_goods'] != 1){
                        $res[$k]['upload_customer_goods'] = $uv['publish']==1 ? 1: -1;
                    }
                }

            }
        }
        $res['total'] = $count[0]['cnt'];

        return $res;
    }

    public function getCashBillListOnePage($customerId, $offset, $length){
        //1.获取全部的提现未还款记录
//         $sql = 'SELECT h.id, h.consume_amount, h.repay_id, h.status,h.customer_id
//                     FROM customer c LEFT JOIN consume_history h ON c.id = h.customer_id 
//                     WHERE c.id = '.$customerId.' AND h.`status` = 1
//                     AND h.amount > 0 AND h.type = 5 ORDER BY h.id DESC LIMIT '.$offset.','.$length;

        $sql = 'SELECT h.id, h.consume_amount, h.repay_id, h.status,h.customer_id
                    FROM customer c LEFT JOIN consume_history h ON c.id = h.customer_id
                    WHERE c.id = '.$customerId.' AND h.`status` = 1
                    AND h.amount > 0 AND h.type = 5 ORDER BY h.id DESC LIMIT '.$offset.','.$length;
        
        $billList = M()->query($sql);
//         echo $sql;
        Log::write("账单数据：sql=".$sql, Log::INFO);
        $data = [];
        if($billList){
            $i = 0;
            foreach ($billList as $v) {
                $detail = M('ConsumeInstallmentHistory')->order('repayment_time')->where(['parent_id' => $v['id'], 'status' => 0])->
                field('id, amount, DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date, 
                repayment_time, discount_rebate, add_time')->select();
                
                Log::write("sql=".M()->getLastSql(), Log::DEBUG);
                $repay_conf = M('SysInstallmentPlan')->where(['id' => $v['repay_id'], 'publish' => 1, 'target' => 3])->find();
                foreach ($detail as $key=>$value) {
                    $i++;
                    $detail_data['consume_id'] = $v['id'];
                    $detail_data['status'] =$v['status'];
                    $detail_data['bill_id'] = $value['id'];
                    $detail_data['total_amount'] = $v['consume_amount'];
                    $detail_data['repay_money'] = $value['amount'];
                    $detail_data['total_times'] = $repay_conf['repay_times'];
                    $detail_data['current_times'] = $repay_conf['repay_unit']==2 ? ($key+1) : (intval(date('Y', $value['repayment_time'])) - intval(date('Y', $value['add_time'])))*12
                        + intval(date('n', $value['repayment_time'])) - intval(date('n', $value['add_time']));
                    $detail_data['repay_date'] = date('Y-m-d', $value['repayment_time']);
                    $detail_data['timer'] = $repay_conf['timer'];
                    $detail_data['repay_unit'] = $repay_conf['repay_unit'];
                    $detail_data['is_overdue'] = $value['fine_date'][0] == '-';
                    if ($value['fine_date'][0] == '-') {
                        $fine = $v['consume_amount'] * Constant::WITHDRAWAL_FINE * intval(substr($value['fine_date'], 1));
                        $detail_data['late_fee'] = $fine < 1 ? 1 : ceil($fine - $value['discount_rebate']);
                        $detail_data['repay_amount'] = intval($detail_data['late_fee']) + intval($value['amount']);
                        $detail_data['remainder_repay_days'] = '逾期'.substr($value['fine_date'], 1).'天';
                    }else{
                        $detail_data['repay_amount'] = $value['amount'];
                        $detail_data['remainder_repay_days'] = '剩余'.$value['fine_date'].'天';
                        $detail_data['late_fee'] = 0;
                    }
                    /*********************************新加入预期收取费用50元**********************************/
                    $detail_data['repay_amount']=$detail_data['late_fee']>0?($detail_data['repay_amount']+Constant::OVER_DATE_RATE):($detail_data['repay_amount']);
                    $detail_data['over_date_fee']=$detail_data['late_fee']>0?Constant::OVER_DATE_RATE:0;
                    /*********************************新加入预期收取费用50元**********************************/
                    $data[$value['repayment_time']+$i] = $detail_data;
                    Log::write("账单数据2：" . json_encode($data, JSON_UNESCAPED_UNICODE), Log::INFO);
                }
            }
        }
        
        $res_data = [];
        ksort($data);
        foreach ($data as $v){
            $res_data[] = $v;
        }

        return $res_data;
    }

    public function getCashBillByBillId($consume_id)
    {
        $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->find();
        if(!$consume){
            BusinessException::throwException(Constant::ORDER_ID_NOT_FOUNT);
        }
        /*****产品为1的强制改为3****/
        if($consume['repay_id']==1){
            $consume['repay_id']=3;
        }
        /*********/
        $repay_conf = M('SysInstallmentPlan')->where(['id' => $consume['repay_id'], 'publish' => 1, 'target' => 3])->find();
        if(!$repay_conf){
            BusinessException::throwException(Constant::ERROR_RETURN_DATA);
        }

        $detail = M('ConsumeInstallmentHistory')->order('id')->where(['parent_id' => $consume_id])->
        field('id, parent_id, overdue_amount, amount, DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date, 
        repayment_time, discount_rebate, status, add_time, update_time,allow_renew')->select();
        
        if(!$consume){
            BusinessException::throwException(Constant::ORDER_ID_STATUS_ERROR);
        }
        
        $data1 = date("Y-m-d,H:i:s",time());
        $data2 = date("Y-m-d,H:i:s",$detail[0]['repayment_time']);
        $date=floor((strtotime($data1)-strtotime($data2))/86400);
        
        if(abs($date) <= 3){
            $res_data['amount'] = $consume['consume_amount'];
            $res_data['transfer_amount'] = $consume['amount'];
            $res_data['consume_time'] = date('Y-m-d H:i:s', $consume['add_time']);
            $res_data['repay_times'] = $repay_conf['repay_times'];
            $res_data['repay_unit'] = $repay_conf['repay_unit'];
            //开启费率
            $res_data['cut_interest'] = $repay_conf['cut_interest'];
            $res_data['timer'] = $repay_conf['timer'];
            $res_data['consume_id'] = $consume['id'];
            $res_data['status'] = 14;
            $need_repay_total = $repay_amount = $have_repay = 0;
        }else {
            $res_data['amount'] = $consume['consume_amount'];
            $res_data['transfer_amount'] = $consume['amount'];
            $res_data['consume_time'] = date('Y-m-d H:i:s', $consume['add_time']);
            $res_data['repay_times'] = $repay_conf['repay_times'];
            //开启费率
            $res_data['cut_interest'] = $repay_conf['cut_interest'];
            $res_data['repay_unit'] = $repay_conf['repay_unit'];
            $res_data['timer'] = $repay_conf['timer'];
            $res_data['consume_id'] = $consume['id'];
            $need_repay_total = $repay_amount = $have_repay = 0;
        }
        //$res_data['status'] = 14;//所有用户--都可以续借
        //逾期后|不允许主动展期
        if($detail[0]['repayment_time']>=time()){
            $res_data['status'] = 14;
        }
        if($detail[0]['allow_renew']){
            $res_data['status'] = 14;
        }
        foreach ($detail as $value) {
            $detail_data['id'] = $value['id'];
            $detail_data['principal'] = $value['amount'];
            $detail_data['state'] = $value['status'] ? 0 : 2;
            $detail_data['repay_date'] = date('Y-m-d', $value['repayment_time']);

            if($value['status']){
                $detail_data['late_fee'] = intval($value['overdue_amount']) - intval($value['discount_rebate']);
                $detail_data['time'] = date('m-d', $value['update_time']).'已还';
                $detail_data['repay_amount'] = intval($value['amount']) + $detail_data['late_fee'];
                $have_repay += intval($value['amount']);
            }else{
                if ($value['fine_date'][0] == '-') {
                    $detail_data['state'] = 1;
                    $fine = $consume['consume_amount'] * Constant::WITHDRAWAL_FINE * intval(substr($value['fine_date'], 1));
                    if ($fine >= $consume['consume_amount']){
                        $fine = $consume['consume_amount']-Constant::OVER_DATE_RATE;
                    }
                    $detail_data['late_fee'] = $fine < 1 ? 1 : ceil($fine - $value['discount_rebate']);
                    $detail_data['repay_amount'] = intval($detail_data['late_fee']) + intval($value['amount']);
                    $detail_data['time'] = '逾期'.substr($value['fine_date'], 1).'天';
                }else{
                    $detail_data['repay_amount'] = $value['amount'];
                    $detail_data['time'] = date('m-d', $value['repayment_time']).'待还';
                    $detail_data['late_fee'] = 0;
                }
                //$repay_amount += intval($value['amount']);
                $need_repay_total += intval($detail_data['repay_amount']);
            }
            /*********************************新加入预期收取费用50元**********************************/
            $detail_data['repay_amount']=$detail_data['late_fee']>0?($detail_data['repay_amount']+Constant::OVER_DATE_RATE):($detail_data['repay_amount']);
            if ($detail_data['repay_amount'] >= 2 * $consume['consume_amount']){
                $detail_data['repay_amount'] = 2 * $consume['consume_amount'];
            }
            $detail_data['over_date_fee']=$detail_data['late_fee']>0?Constant::OVER_DATE_RATE:0;
            /*********************************新加入预期收取费用50元**********************************/
            $res_data['list'][] = $detail_data;
            Log::write("账单数据2：" . json_encode($detail_data, JSON_UNESCAPED_UNICODE), Log::DEBUG);
        }
        //$res_data['repay_amount'] = $repay_amount;
        $res_data['have_repay'] = $have_repay;
        $res_data['need_repay_total'] = $need_repay_total;

        return $res_data;
    }

    /*** 获取用户分期消费的总待还款条数 ***/
    public function getConsumeCountWaitRepay($customer_id)
    {
        //获取次月待还款的总条数
        $sql = 'SELECT count(1) AS cnt
                FROM customer c LEFT JOIN consume_history h ON c.id = h.customer_id 
                LEFT JOIN merchant m ON h.merchant_id = m.id 
                WHERE c.id = '.$customer_id.' AND h.`status` = 1
                AND h.amount > 0 AND h.type = 1 AND c.type = 1';
        $res = $this->query($sql);
        $count['next_cnt'] = $res[0]['cnt'];
        $count['all_cnt'] = $res[0]['cnt'];

        //获取分期待还款的总条数
        $sql = 'SELECT count(1) AS cnt
                FROM customer c LEFT JOIN consume_history h ON c.id = h.customer_id 
                LEFT JOIN merchant m ON h.merchant_id = m.id
                LEFT JOIN consume_installment_history i ON h.id = i.parent_id
                WHERE c.id = '.$customer_id.' AND h.`status` IN (1, 4) 
                AND h.amount > 0 AND h.type = 2 AND i.status = 0 AND c.type = 1';
        $res = $this->query($sql);
        $count['all_cnt'] += $res[0]['cnt'];
        $count['installment_cnt'] = $res[0]['cnt'];

        return $count;
    }

    public function getBillListOnePage($customerId, $offset, $length, $nextCnt){
        $data = [];
        if($offset < $nextCnt){
            //1.获取次月还款记录
            $sql = 'SELECT h.id AS consume_id,h.customer_id, h.status, m.name AS merchant_name, m.logo AS merchant_logo, h.type AS repay_type, c.type AS customer_type,
                    FROM_UNIXTIME(h.repayment_time, "%Y-%m-%d") AS repay_date, h.amount AS repay_amount, h.consume_amount AS total_amount, h.discount_rebate,
                    h.discount_first_order+h.discount_full_reduce AS discount, DATEDIFF(CURDATE(),FROM_UNIXTIME(h.repayment_time, "%Y-%m-%d")) AS fine_date,
                    FROM_UNIXTIME(h.add_time, "%Y-%m-%d") AS consume_date
                    FROM customer c LEFT JOIN consume_history h ON c.id = h.customer_id 
                    LEFT JOIN merchant m ON h.merchant_id = m.id 
                    WHERE c.id = '.$customerId.' AND h.`status` = 1 
                    AND h.amount > 0 AND h.type = 1 AND c.type = 1 ORDER BY h.id DESC LIMIT '.$offset.','.$length;
            $billList = M()->query($sql);
            Log::write("账单数据：sql=".$sql, Log::INFO);
            if(count($billList)){
                foreach ($billList as $v) {
                    $v['current_time'] = 1;
                    $v['total_times'] = 1;
                    $v['real_pay'] = $v['repay_amount'];
                    //临时写在这里，后面提取取来
                    if ($v['fine_date'][0] != '-' && intval($v['fine_date']) > 0) {//已经逾期
                        if (1 == $v['customer_type']) {
                            $fine = $v['repay_amount'] * ConsumeHistoryModel::STATUS_FAXI * intval($v['fine_date']); //利息低于1分按1分算
                        }
                        if (2 == $v['customer_type']) {
                            $fine = $v['repay_amount'] * 0.001 * intval($v['fine_date']); //利息低于1分按1分算
                        }
                        $v['fine'] = $fine < 1 ? 1 : ceil($fine - $v['discount_rebate']);
                        $v['all_pay'] = intval($v['fine']) + intval($v['repay_amount']);
                    }
                    $data[] = $v;
                }
            }
        }else{
            $offset -= $nextCnt%$length;
        }

        //获取分期还款记录
        if(count($data) < $length){
            $length -= count($data);
            $sql = 'SELECT i.amount AS repay_amount, FROM_UNIXTIME(i.repayment_time, "%Y-%m-%d") AS repay_date, h.repay_id,
                    DATEDIFF(CURDATE(),FROM_UNIXTIME(i.repayment_time,"%Y-%m-%d")) AS fine_date, i.repayment_time, i.add_time, i.discount_rebate,
                    h.id AS consume_id,h.customer_id, h.status, m.name AS merchant_name, m.logo AS merchant_logo, h.type AS repay_type, 
                    c.type AS customer_type, h.amount AS real_pay, h.consume_amount AS total_amount, 
                    h.discount_first_order+h.discount_full_reduce+h.discount_rebate_amount AS discount, FROM_UNIXTIME(h.add_time, "%Y-%m-%d") AS consume_date
                    FROM customer c LEFT JOIN consume_history h ON c.id = h.customer_id 
                    LEFT JOIN merchant m ON h.merchant_id = m.id
                    LEFT JOIN consume_installment_history i ON h.id = i.parent_id
                    WHERE c.id = '.$customerId.' AND h.`status` IN (1, 4) 
                    AND h.amount > 0 AND h.type = 2 AND i.status = 0 AND c.type = 1 ORDER BY i.repayment_time LIMIT '.$offset.','.$length;

            $install = M()->query($sql);

            Log::write("账单数据2：sql=".$sql, Log::INFO);

            if(count($install)){
                $times = [];
                foreach ($install as $k=>$value){
                    if(!isset($times[$value['repay_id']])){
                        $repay_conf = M('SysInstallmentPlan')->where(['id' => $value['repay_id'], 'publish' => 1, 'target' => 3])->find();
                        if($repay_conf){
                            $times[$value['repay_id']] = $repay_conf['repay_times'];
                        }else{
                            $times_sql = 'SELECT count(1) AS cnt FROM consume_installment_history WHERE parent_id = '.$value['consume_id'];
                            $all_times = M()->query($times_sql);
                            $times[$value['repay_id']] = $all_times[0]['cnt'];
                        }
                    }
                    $value['total_times'] = $times[$value['repay_id']];
                    $value['current_time'] = (intval(date('Y', $value['repayment_time'])) - intval(date('Y', $value['add_time'])))*12
                        + intval(date('n', $value['repayment_time'])) - intval(date('n', $value['add_time']));
                    if($value['fine_date'][0] != '-' && intval($value['fine_date']) > 0){
                        if(1 == $value['customer_type']) {
                            $fine = $value['real_pay'] * ConsumeHistoryModel::STATUS_FAXI * intval($value['fine_date']); //利息低于1分按1分算
                        }
                        if(2 == $value['customer_type']) {
                            $fine = $value['real_pay'] * 0.001 * intval($value['fine_date']); //利息低于1分按1分算
                        }
                        $value['fine'] = $fine < 1 ? 1 : ceil($fine-$value['discount_rebate']);
                        $value['all_pay'] = intval($value['fine']) + intval($value['repay_amount']);
                    }else{
                        $value['fine'] = 0;
                        $value['all_pay'] = $value['repay_amount'];
                    }
                    $data[] = $value;
                }
            }
        }

        return $data;
    }

     
    /******
     * 获取大单条数
     ******/
    public function bigBillCount($customer_id){
        $sql = 'SELECT count(*) AS cnt FROM consume_history h 
                LEFT JOIN customer c ON c.id = h.customer_id
                WHERE h.customer_id = '.$customer_id.' AND h.`status` IN (1,4)
                 AND h.amount > 0 AND h.type IN (1,2) AND c.type = 1';
        Log::write("获取大单条数sql：".$sql, Log::INFO);
        $res = $this->query($sql);
        if($res[0]['cnt']==1){
            $sql = 'SELECT h.id AS consume_id FROM consume_history h  WHERE h.customer_id = '.$customer_id.' AND h.`status` IN (1,4) AND h.amount > 0 AND h.type IN (1,2)';
            $ret = $this->query($sql);
            return array($res[0]['cnt'],$ret);
        }
        return array($res[0]['cnt']);

    }
    /**获取大单**/
    public function getBillData($customerId){
            $data = [];
            $sql = 'SELECT h.amount AS repay_amount, FROM_UNIXTIME(h.repayment_time, "%Y-%m-%d") AS repay_date, h.repay_id,h.down_payment,DATEDIFF(CURDATE(),FROM_UNIXTIME(h.repayment_time,"%Y-%m-%d")) AS fine_date, h.repayment_time, h.add_time, h.discount_rebate,h.id AS consume_id,h.customer_id, h.status, m.name AS merchant_name, m.logo AS merchant_logo, h.type AS repay_type,c.type AS customer_type, h.amount AS real_pay, h.consume_amount AS total_amount,h.discount_first_order+h.discount_full_reduce+h.discount_rebate_amount AS discount, FROM_UNIXTIME(h.add_time, "%Y-%m-%d %H:%i") AS consume_date, m.add_time AS create_time
                    FROM customer c LEFT JOIN consume_history h ON c.id = h.customer_id 
                    LEFT JOIN merchant m ON h.merchant_id = m.id
                    WHERE c.id = '.$customerId.' AND h.`status` IN (1,4) 
                    AND h.amount > 0 AND h.type IN (1,2) AND c.type = 1 ORDER BY h.repayment_time';
            $install = M()->query($sql);
            if(count($install)){//大单存在
                $times = [];
                foreach ($install as $k=>$value){
                  if(!isset($times[$value['repay_id']])){
                   $repay_conf = M('SysInstallmentPlan')
                                ->where(['id' => $value['repay_id'], 'target' => 1])
                                ->find();
                   if($repay_conf){
                            $times[$value['repay_id']] = $repay_conf['repay_times'];//分期总次数
                   }else{
                            $times_sql = 'SELECT count(1) AS cnt FROM consume_installment_history WHERE parent_id = '.$value['consume_id'];
                            $all_times = M()->query($times_sql);
                            $times[$value['repay_id']] = $all_times[0]['cnt'];
                        }
                    }
                    $value['total_times'] = $times[$value['repay_id']];//分期总次数
                    $value['current_time'] = (intval(date('Y', $value['repayment_time'])) - intval(date('Y', $value['add_time'])))*12 + intval(date('n', $value['repayment_time'])) - intval(date('n', $value['add_time']));
                    if($value['repay_type']==2){//已经分期
                        $i_fine = $i_amount = 0;
                        $sql = "SELECT amount,DATEDIFF(CURDATE(),FROM_UNIXTIME(repayment_time,\"%Y-%m-%d\")) AS fine_date,discount_rebate FROM consume_installment_history WHERE status=0 AND parent_id = ".$value['consume_id']." AND repayment_time <= ".strtotime($value['repay_date'])." Limit ".$value['current_time'];
                        $i_arr = M()->query($sql);
                        if(count($i_arr)){
                            foreach ($i_arr as $v){
                                $i_amount = $i_amount+$v['amount'];
                                if($v['fine_date'][0] != '-' && intval($v['fine_date']) > 3){
                                  $fine_i = $value['real_pay'] * ConsumeHistoryModel::STATUS_FAXI * intval($v['fine_date']); //逾期费用
                                  $i_fine = $i_fine +($fine_i < 1 ? 1 : ceil($fine_i-$v['discount_rebate']));
                                }
                            }
                            $i_fine = ceil($i_fine/100)*100;
                        }
                        $value['repay_amount'] = $i_amount + $i_fine;
                    }

                    if($value['fine_date'][0] != '-' && intval($value['fine_date']) > 3){//已经逾期
                        $fine = $value['real_pay'] * ConsumeHistoryModel::STATUS_FAXI * intval($value['fine_date']); //逾期费用
                        $value['fine'] = $fine < 1 ? 1 : ceil($fine-$value['discount_rebate']);
                        $value['fine'] = ceil($value['fine']/100)*100;
                    }else{
                        $value['fine'] = 0;
                    }
                    $data[] = $value;
                }
            }
        Log::write("大单数据：".json_encode($data),Log::DEBUG);
        return $data;
    }


    /**获取小单**/
    public function getSmallBill($consume_id){
        $consume = M('ConsumeHistory')->where(['id'=>$consume_id])->field('id,customer_id,merchant_id,type,FROM_UNIXTIME(add_time, "%Y-%m-%d %H:%i") AS consume_date,status,DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date,amount,parent_id,repayment_time,consume_amount,down_payment,repay_id,add_time,FROM_UNIXTIME(repayment_time, "%Y-%m-%d") AS repay_date')->find();
        //获取商家信息
        $info = M('Merchant')->where(['id'=>$consume['merchant_id']])->field('name AS merchant_name,logo AS merchant_logo, add_time AS create_time')->find();
        //分期利率表信息
        $times = 0;
        $repay_conf = M('SysInstallmentPlan')->where(['id' => $consume['repay_id'], 'target' => 1])->find();
        if($repay_conf){
            $times = $repay_conf['repay_times'];
        }
        if(!$times){
            $times_sql = 'SELECT count(1) AS cnt FROM consume_installment_history WHERE parent_id = '.$consume['id'];
            $all_times = M()->query($times_sql);
            $times = $all_times[0]['cnt'];
        }
        $res_data['consume_id'] = $consume['id'];//消费id
        $res_data['merchant_name'] = $info['merchant_name'];//商户名称
        $res_data['merchant_logo'] = $info['merchant_logo'];//商户logo
        $res_data['create_time'] = $info['create_time']; //商户创建时间
        $res_data['repay_type'] = $consume['type'];//还款类型1:次月还款,2:分期付款
        $res_data['consume_date'] = $consume['consume_date'];//消费日期
        $res_data['amount'] = $consume['consume_amount'];//消费总金额
        $res_data['down_payment'] = $consume['down_payment'];//首付金额
        $res_data['borrow_amount'] = intval($consume['amount']);//买呗代付金额
        $res_data['total_times'] = $times;//分期总期数

     if($res_data['total_times']==1){//未分期，即次月还款
            $res_data['current_time'] = 1;//当前期数
            if ($consume['fine_date'][0] == '-') {//逾期未还
                $detail_data['state'] = 1;
                    if(intval(substr($consume['fine_date'], 1))>3){
                        $fine = $consume['amount'] * ConsumeHistoryModel::STATUS_FAXI * intval(substr($consume['fine_date'], 1));
                    }else{
                        $fine = 0;
                    }
                $detail_data['late_fee'] = $fine < 1 ? 1 : ceil($fine - $consume['discount_rebate']);
                $detail_data['repay_amount'] = $detail_data['late_fee'] + $consume['amount'];
                $detail_data['time'] = '逾期'.substr($consume['fine_date'], 1).'天';
            }else{//未逾期，最后还款时间还没到
                $detail_data['repay_amount'] = $consume['amount'];
                $detail_data['time'] = date('m-d', $consume['repayment_time']).'待还';
                $detail_data['late_fee'] = 0;
                $detail_data['state'] = 2;
            }
            $res_data['repay_amount'] = $detail_data['repay_amount'];//待还总金额
            $res_data['have_repay'] = 0;//已还金额
            $res_data['small_order_list'][0]['id'] = $consume['id'];
            $res_data['small_order_list'][0]['principal'] = $consume['amount'];
            $res_data['small_order_list'][0]['late_fee'] = ceil($detail_data['late_fee']);//逾期金额，没有逾期返回0
            $res_data['small_order_list'][0]['time'] = $detail_data['time'];//还款时间
            $res_data['small_order_list'][0]['repay_date'] = $consume['repay_date'];//还款时间
            $res_data['small_order_list'][0]['state'] = $detail_data['state'];//账单状态，0：已还，1：待还有逾期，2：待还无逾期
            $res_data['small_order_list'][0]['repay_amount'] = $detail_data['repay_amount'];
            $res_data['small_order_list'][0]['need_pay'] = ceil($detail_data['repay_amount']);//未分期 需付款金额即为未还款的总金额
            $res_data['small_order_list'][0]['save_amount'] = ceil($res_data['small_order_list'][0]['repay_amount']-$res_data['small_order_list'][0]['need_pay']);//节省金额
            //小对话框
            $prin = ceil($consume['amount'])/100;
            $lee = ceil($res_data['small_order_list'][0]['late_fee'])/100;
            $res_data['small_order_list'][0]['money_data'][0] = array('name'=>'本金','money'=>$prin) ;
            $res_data['small_order_list'][0]['money_data'][1] = array('name'=>'服务费','money'=>'0') ;
            $res_data['small_order_list'][0]['money_data'][2] = array('name'=>'逾期费','money'=>$lee) ;
        }
     //已经分期
     else{
            $detail = M('ConsumeInstallmentHistory')->order('id')->where(['parent_id' => $consume_id])->
            field('id, parent_id, overdue_amount, amount, DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date,repayment_time, discount_rebate,FROM_UNIXTIME(repayment_time, "%Y-%m-%d") AS repay_date, status, add_time, update_time')->select();
            $res_data['current_time'] = (intval(date('Y', $consume['repayment_time'])) - intval(date('Y', $consume['add_time'])))*12+ intval(date('n', $consume['repayment_time'])) - intval(date('n', $consume['add_time']));//当前期数
            $prin_month = ceil($consume['amount']/$res_data['total_times']/100)*100;//每月本金
            $repay_amount = $have_repay = $penalty = $pein = $server = $must_server = $late_lee_all = 0;
            foreach ($detail as $k=>$value) {
                $fine = 0;
                $detail_data['id'] = $value['id'];
                if($value['status']){//$value['status']=1 已经还款
                    $detail_data['state'] = 0;
                    $detail_data['late_fee'] = intval($value['overdue_amount']) - intval($value['discount_rebate']);
                    $detail_data['time'] = date('m-d', $value['update_time']).'已还';
                    $detail_data['repay_amount'] =  $detail_data['late_fee']+$value['amount'];
                }else{
                    //未还款
                    if ($value['fine_date'][0] == '-') {//逾期未还
                        $detail_data['state'] = 1;
                        if(intval(substr($value['fine_date'], 1))>3){
                            $fine = $consume['amount'] * ConsumeHistoryModel::STATUS_FAXI * intval(substr($value['fine_date'], 1));
                            $fine =  $fine < 1 ? 1 : ceil($fine - $value['discount_rebate']);
                        }
                        $late_lee_all += $fine; //弹框逾期金额
                        $detail_data['late_fee'] = $fine;
                        $detail_data['repay_amount'] = ceil($fine+ $value['amount']);
                        $detail_data['time'] = '逾期'.substr($value['fine_date'], 1).'天';
                    }else{//未逾期未还
                        $detail_data['repay_amount'] = $value['amount'];
                        $detail_data['time'] = date('m-d', $value['repayment_time']).'待还';
                        $detail_data['late_fee'] = 0;
                        $detail_data['state'] = 2;
                    }

                    //累积必须还的服务费金额
                    if($value['repay_date'] <= date('Y-m-d', get_repayment_date(1))){
                        $must_server +=  $value['amount'] - $prin_month;
                    }

                    $pein += $prin_month; //弹框本金
                    $server += $value['amount'] - $prin_month; //弹框服务费
                    $repay_amount = ceil($repay_amount + $detail_data['repay_amount']); //未还总额
                }

                $res_data['small_order_list'][$k]['id'] = $value['id'];
                $res_data['small_order_list'][$k]['principal'] = $value['amount'];
                $res_data['small_order_list'][$k]['late_fee'] = $fine;//逾期金额
                $res_data['small_order_list'][$k]['time'] = $detail_data['time'];//已经还款的格式：08-10已还，逾期的格式：逾期6天，未到期的格式：11-10待还
                $res_data['small_order_list'][$k]['repay_date'] = $value['repay_date'];//还款时间
                $res_data['small_order_list'][$k]['state'] = $detail_data['state'];//账单状态，0：已还，1：待还有逾期，2：待还无逾期
                $res_data['small_order_list'][$k]['repay_amount'] = $value['amount']+$fine;//本笔应还总金额（本笔的本金+利息+罚金）
                $res_data['small_order_list'][$k]['need_pay'] = $repay_amount; //累积未还总额

                $res_data['small_order_list'][$k]['money_data'][0] = array('name'=>'本金','money'=>$pein/100);
                $res_data['small_order_list'][$k]['money_data'][1] = array('name'=>'服务费','money'=>$server/100);
                $res_data['small_order_list'][$k]['money_data'][2] = array('name'=>'逾期费','money'=>sprintf ('%s', $late_lee_all/100)) ;

                //计算违约金
                if($k+1==$res_data['total_times']){
                    if($detail[0]['status'] == 0){
                        $res_data['small_order_list'][$k]['money_data'][0] = array('name'=>'本金','money'=>$consume['amount']/100);
                        $server = $must_server ? $value['amount']*$times - $consume['amount'] : $server;
                    }
                    if($server-$must_server >= Constant::PENALTY){
                        $penalty = Constant::PENALTY;
                    }else{
                        $penalty = $server-$must_server;
                    }
                    Log::write("fuwu=".$must_server, Log::DEBUG);
                    $res_data['small_order_list'][$k]['money_data'][1] = array('name'=>'服务费','money'=>$must_server/100);
                    $res_data['small_order_list'][$k]['save_amount'] = $server-$must_server-$penalty;//节省金额
                    $res_data['small_order_list'][$k]['need_pay'] = $repay_amount - $res_data['small_order_list'][$k]['save_amount'];
                    $res_data['small_order_list'][$k]['money_data'][3] = array('name'=>'违约金','money'=>$penalty/100);
                }

                /*if($res_data['small_order_list'][$res_data['current_time']-1]['state'] == 0){//当月已经还款
                    $interest = $interest_month*($k+1-$res_data['current_time']);
                    $server = 0;

                    //弹框本金展示
                    if($k+1 == $res_data['total_times'] && $have_repay == 0){
                        $pein = $consume['amount'];
                    }elseif($k+1 == $res_data['total_times'] && $have_repay > 0){
                        $num = $have_repay/$value['amount'];
                        $pein = $consume['amount']-$prin_month*$num;
                    }elseif($k+1 != $res_data['total_times'] && $have_repay > 0){
                        $num = $have_repay/$value['amount'];
                        $pein = $fine_p[$k]-$prin_month*$num;
                    }elseif($k+1 != $res_data['total_times'] && $have_repay == 0){
                        $pein = $fine_p[$k];
                    }

                    //最后一期
                    if($k+1==$res_data['total_times']){
                        if($interest>=26000){
                            $penalty = 26000;
                        }else{
                            $penalty = $interest;
                        }
                    }
                    $res_data['small_order_list'][$k]['need_pay'] = $pein + $penalty  + ceil($late_lee_all);
                    Log::write("本金：".$pein."服务费：".$server."利息：".$interest,Log::DEBUG);
                    $res_data['small_order_list'][$k]['money_data'][0] = array('name'=>'本金','money'=>$pein/100);

                    $res_data['small_order_list'][$k]['money_data'][1] = array('name'=>'服务费','money'=>$server/100) ;
                }else{
                    $interest = $interest_month*($k+2-$res_data['current_time']);

                    if($fine_i>0){
                        $server =  $interest_month*($fine_i+1);
                    }else{
                        $server = $interest_month*($k+2-$res_data['current_time']);
                    }
                    if($k+1 == $res_data['total_times'] && $have_repay == 0){
                        $pein = $consume['amount'];
                    }elseif($k+1 == $res_data['total_times'] && $have_repay > 0){
                        $num = $have_repay/$value['amount'];
                        $pein = $consume['amount']-$prin_month*$num;
                    }elseif($k+1 != $res_data['total_times'] && $have_repay > 0){
                        $num = $have_repay/$value['amount'];
                        $pein = $fine_p[$k]-$prin_month*$num;
                    }elseif($k+1 != $res_data['total_times'] && $have_repay == 0){
                        $pein = $fine_p[$k];
                    }
                    //最后一期
                    if($k+1==$res_data['total_times']){
                        if($interest>=26000){
                            $server = $interest_month;
                            $penalty = 26000;//违约金
                            $interest = $server + $penalty;//违约金+服务费
                        }else{
                            $penalty = $interest-$server;
                        }
                    }
                    $res_data['small_order_list'][$k]['need_pay']= $pein + $interest + ceil($late_lee_all);
                    $res_data['small_order_list'][$k]['money_data'][0] = array('name'=>'本金','money'=>$pein/100);
                    $res_data['small_order_list'][$k]['money_data'][1] = array('name'=>'服务费','money'=>$server/100);
                }*/
            }
            $res_data['repay_amount'] = $repay_amount;//待还总金额
            $res_data['have_repay'] = $have_repay;//已还金额
        }

        return $res_data;
    }

    /*********
     * 付款校对
     * $big_id   string 大单数据id
     * $small_id  string  小单数据
     * *******/
    public function PaymentCheck($big_id,$small_id)
    {
        $small_id = explode(",",$small_id);
        //判断$small_id是否为数组
        if (!is_array($small_id)) {
            BusinessException::throwException(Constant::INVALID_PARAMETER);
        }
        $consume = M('ConsumeHistory')->where(['id' => $big_id])->field('amount,repay_id,discount_rebate')->find();//大单数据
        $k = count($small_id);
        $repay_amount = $late_fee =  $late_lee_all =  $must_server = 0;
        if ($k == 1) {//只还一期
            $detail = M('ConsumeInstallmentHistory')->where(['id' => $small_id[0]])->field('amount, DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date,repayment_time,discount_rebate')->find();
            if ($detail['fine_date'][0] == '-' && intval(substr($detail['fine_date'], 1))>0) {//逾期未还
                if (intval(substr($detail['fine_date'], 1)) > 3) {
                    $fine = $consume['amount'] * ConsumeHistoryModel::STATUS_FAXI * intval(substr($detail['fine_date'], 1));
                    $fine = $fine < 1 ? 1 : ceil($fine - $detail['discount_rebate']);//逾期金额
                } else {
                    $fine = 0;
                }
            }

            $late_fee = $late_fee + $fine;
            $repay_amount = ceil($repay_amount + $detail['amount'] + $late_fee);
        }
        else {//还多期
            rsort($small_id);//从高到低排列
            //查询所有期数
            $repay_conf = M('SysInstallmentPlan')->where(['id' => $consume['repay_id'], 'target' => 1])->find();
           if ($repay_conf) {
              $times_all = $repay_conf['repay_times'];
           } else {
              $times_sql = 'SELECT count(1) AS cnt FROM consume_installment_history WHERE parent_id = ' . $big_id;
              $all_times = M()->query($times_sql);
              $times_all = $all_times[0]['cnt'];//总分期数
           }
           $detail = M('ConsumeInstallmentHistory')->where(['id' => $small_id[$k-1]])->field('amount, DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date,discount_rebate,repayment_time')->find();

            Log::write('数据啊'.json_encode($detail),Log::DEBUG);
           $sql = 'SELECT count(1) AS cnt FROM consume_installment_history WHERE status = 1 AND parent_id = ' . $big_id;
           $old_times = M()->query($sql);
           $all_old = $old_times[0]['cnt'];
            $principal_month = ceil($consume['amount']/$times_all/100)*100;//每月的本金
            $interest_month = $detail['amount']-$principal_month;//每一期的利息


      /*

           if(($all_old+$k) == $times_all){//提前还款到最后一期
             if($interest>=26000){
                 $interest = 26000 + $interest_month;
                 //第一期是否为本月
                 $BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
                 $begin_day = strtotime($BeginDate);
                 $last_day = strtotime("$BeginDate +1 month -1 day");
                 if(($detail['repayment_time']<=$last_day && $detail['repayment_time']>= $begin_day) ){//
                     $interest = 26000;
                 }
             }

           }*/
         ///全部逾期金额
          for($j=0;$j<$k;$j++){
             $vv = M('ConsumeInstallmentHistory')->where(['id' => $small_id[$j]])->field('DATEDIFF(FROM_UNIXTIME(repayment_time,"%Y-%m-%d"), CURDATE()) AS fine_date,FROM_UNIXTIME(repayment_time, "%Y-%m-%d") AS repay_date')->find();

              //累积必须还的服务费金额
              if($vv['repay_date'] <= date('Y-m-d', get_repayment_date(1))){
                  $must_server +=  $detail['amount'] - $principal_month;
              }


              if ($vv['fine_date'][0] == '-' && intval(substr($detail['fine_date'], 1))>0) {//逾期未还
               if (intval(substr($vv['fine_date'], 1)) > 3) {
                  $fine = $consume['amount'] * ConsumeHistoryModel::STATUS_FAXI * intval(substr($vv['fine_date'], 1));
                  $fine =  $fine < 1 ? 1 : ceil($fine - $detail['discount_rebate']);
               } else {
                  $fine = 0;
               }
                 $late_lee_all = $late_lee_all + $fine;
            }
        }



            //计算利息---------
            $principal = $principal_month*$k;
            $interest = ($interest_month)*$k;//要还得利息

           $repay_amount = $repay_amount + $late_lee_all + $interest + $principal;

            if($k==$times_all){
                $interest = $detail['amount']*$k - $consume['amount'];
                if($interest>=26000){
                    $save = $interest-26000;
                    $repay_amount = $consume['amount']  + $late_lee_all + 26000 + $must_server ;
                }else{
                    $repay_amount = $detail['amount']*$k + $late_lee_all ;
                }
            }
            if($all_old>0){
                $interest = $interest-$must_server;
                if($interest>=26000){
                    $save = $interest-26000;
                    $repay_amount = $detail['amount']*$k + $late_lee_all - $save;
                }else{
                    $repay_amount = $detail['amount']*$k + $late_lee_all ;
                }
            }

        }
     Log::write("zuihoude:".$repay_amount.'lixi:'.$interest,Log::DEBUG);
     return $repay_amount;
    }


    /**
     * 获取指定天数内某业务员的订单
     * @param $admin_id
     * @param $days
     * @return mixed
     */
    public function getClerkOrder($admin_id, $days, $offset=0, $length=10)
    {
        $Model = M('ConsumeHistory');
        $map = array(
            'h.status' => ['in', '1, 4, 2, 8, 12, 15, 17, 16'],
            'h.type'   => ['in', '1, 2, 4'],
            'v.status' => ['in', '6, 7, 9'],
            'v.opr_id' => $admin_id,
            'DATEDIFF(SYSDATE(), v.add_time)' => ['LT', $days],
            'c.type'   => ['in', '1, 3']
        );
        $count = $Model->alias('h')
            ->join('credit_vetting v ON h.id = v.consume_id')
            ->join('customer c on h.customer_id = c.id')
            ->join('LEFT JOIN sys_installment_plan p on p.id = h.repay_id')
            ->where($map)->group('h.id')->count();

        $ret = $Model->alias('h')
            ->join('credit_vetting v ON h.id = v.consume_id')
            ->join('customer c on h.customer_id = c.id')
            ->join('LEFT JOIN sys_installment_plan p on p.id = h.repay_id')
            ->field('IF(h.type=5, "现金贷订单", IF(v.status=9, "担保分期订单", IF(h.discount_interest=2,"优惠分期订单", "普通分期订单"))) AS discrition, c.id AS customer_id,
                    c.real_name, c.mobile, c.gender, FROM_UNIXTIME(h.add_time, "%Y-%m-%d %H:%i:%s") AS add_time, h.consume_amount, p.repay_times, h.status, h.goods_imei,
                    h.id AS consume_id')
            ->where($map)->group('h.id')->order('v.add_time DESC')->limit($offset, $length)->select();

        Log::write('sql='.M()->getLastSql(), Log::DEBUG);

        $res['total'] = $count;
        $res['res'] = $ret;

        return $res;
    }

    public function getUploadType($consume_id)
    {
        $Model = M('ConsumeHistory');
        $map = [
            'c.status' => 1,
            'h.id' => $consume_id
        ];

        $ret = $Model->alias('h')
            ->join('merchant m on h.merchant_id=m.id')
            ->join('upload_category c on m.category=c.category_id')
            ->field('c.upload_type, c.type_name')
            ->where($map)->select();
        if($ret){
            foreach($ret as $k=>$v){
                $Model = M('UploadConsumeRes');
                $upload = $Model->alias('r')
                    ->join('upload_file f ON f.id = r.upload_id')
                    ->where(['r.consume_id'=>$consume_id, 'f.type'=>$v['upload_type']])->select();
                Log::write("sql=".$Model->getLastSql(), Log::DEBUG);

                $ret[$k]['upload_ok'] = 0;
                foreach ($upload as $uv){
                    if($ret[$k]['upload_ok'] != 1){
                        $ret[$k]['upload_ok'] = $uv['publish']==1 ? 1: -1;
                    }else{
                        break;
                    }
                }

            }
        }
        Log::write('sql='.$Model->getLastSql(), Log::DEBUG);

        return $ret;
    }

}

